package io.github.wslxm.springbootplus2.starter.captcha.controller;

import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.spring.plugins.secondary.SecondaryVerificationApplication;
import io.github.wslxm.springbootplus2.starter.captcha.model.CheckCaptchaData;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;
/**
 * 行为验
  * https://gitee.com/dromara/tianai-captcha
  * @author 王松
  * @mail  1720696548@qq.com
  * @date  2025/5/15 13:28
  */
@RestController
@RequestMapping("/api/open/captcha")
@Tag(name = "Captcha --> 行为验")
public class CaptchaController {

    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

    @Operation(summary = "获取行为验", description = "type 验证码类型支持参数: SLIDER /ROTATE /CONCAT /WORD_IMAGE_CLICK (RANDOM=随机)")
    @PostMapping("/gen")
    public Object genCaptcha(String type) {
        // CaptchaResponse<ImageCaptchaVO>
        // CaptchaTypeConstant.SLIDER
        if ("RANDOM".equals(type)) {
            int i = ThreadLocalRandom.current().nextInt(0, 4);
            if (i == 0) {
                type = CaptchaTypeConstant.SLIDER;
            } else if (i == 1) {
                type = CaptchaTypeConstant.CONCAT;
            } else if (i == 2) {
                type = CaptchaTypeConstant.ROTATE;
            } else{
                type = CaptchaTypeConstant.WORD_IMAGE_CLICK;
            }
        }
        return imageCaptchaApplication.generateCaptcha(type);
    }


    @Operation(summary = "验证行为验", description = "")
    @PostMapping("/check")
    public Object checkCaptcha(@RequestBody CheckCaptchaData data) {
        ApiResponse<?> response = imageCaptchaApplication.matching(data.getId(), data.getData());
        if (response.isSuccess()) {
            // 验证码验证成功，此处应该进行自定义业务处理， 或者返回验证token进行二次验证等。
            return ApiResponse.ofSuccess(Collections.singletonMap("validToken", data.getId()));
        }
        return response;
    }

    /**
     * 二次验证，一般用于机器内部调用，这里为了方便测试
     * @param id id
     * @return boolean
     */
    @GetMapping("/check2")
    @ResponseBody
    @Operation(summary = "二次验证，一般用于机器内部调用，这里为了方便测试", description = "")
    public boolean check2Captcha(@RequestParam("id") String id) {
        // 如果开启了二次验证
        if (imageCaptchaApplication instanceof SecondaryVerificationApplication) {
            return ((SecondaryVerificationApplication) imageCaptchaApplication).secondaryVerification(id);
        }
        return false;
    }
}
